<?php

namespace app\company\service\user_profile\userArchive\crisisTesting;

use app\admin\service\user_profile\userArchive\evaluationArchive\EvaluationArchiveService;
use app\admin\service\UserService;
use app\common\Message;
use app\model\InterfereUserModel;
use app\model\UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Service;

class CrisisTestingService extends Service
{
    use Message;

    /**
     * @param $data
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOverview($data): bool
    {
        //用户基本信息
        $getUserInfo = new EvaluationArchiveService($this->app);
        $info = $getUserInfo->getUserInfo($data);
        //危机干预档案统计
        if(check_array_key('isAbandon',$data)){
            //废弃档案
            $wheres = [
                ['uid','=',$data['user_id']],
                ['status','=',1],
                ['is_repeal','=',1],
            ];
        }else{
            //正常档案
            $wheres = [
                ['uid','=',$data['user_id']],
                ['status','=',1],
                ['is_repeal','=',0],
            ];
        }
        $field = ['id,uid,move_time,channel'];
        $recode = InterfereUserModel::query()->where($wheres)->field($field)->select();
        $totalCount = count($recode);
        if($totalCount>0){
            $ret = [
                'min_time' => 0,//档案首次建立时间
                'to_date' => 0,//距今天数
                'total' => count($recode),//总数
                'crisis_reporting' => 0,  //危机上报(来源)
                'crisis_reporting_proportion' => 0,
                'assessment_task' => 0,  //测评任务(来源)
                'assessment_task_proportion' => 0,
                'online_consultation' => 0, //线上咨询(来源)
                'online_consultation_proportion' => 0,
                'offline_reservation' => 0, //线上咨询(来源)
                'offline_reservation_proportion' => 0,
                'follow_user' => 0, //关注人群(来源)
                'follow_user_proportion' => 0,
            ];
            if ($ret['total'] > 0) {
                $timeArray = array_column($recode->toArray(), 'move_time');
                $ret['min_time'] = min($timeArray);
                $ret['max_time'] = max($timeArray);
                $ret['to_date'] = ceil((time() - $ret['min_time']) / (24 * 60 * 60));
                // 初始化来源统计数组
                $sourceCount = array_fill_keys([1, 2, 5, 6, 7], 0);
                // 统计每种来源的数量
                foreach ($recode as $item) {
                    if (isset($sourceCount[$item['channel']])) {
                        $sourceCount[$item['channel']]++;
                    }
                }
                // 映射渠道到返回结果结构
                $channelMapping = [
                    1 => 'crisis_reporting',
                    2 => 'assessment_task',
                    5 => 'online_consultation',
                    6 => 'offline_reservation',
                    7 => 'follow_user',
                ];
                // 更新返回结果
                foreach ($sourceCount as $channel => $count) {
                    if (isset($channelMapping[$channel])) {
                        $ret[$channelMapping[$channel]] = $count;
                        $proportionKey = $channelMapping[$channel] . '_proportion';
                        $ret[$proportionKey] = $totalCount > 0 ? removeTrailingZero(number_format($count / $totalCount * 100, 1)) : 0;
                    }
                }
            }
            $info['intervention_overview'] = $ret;
        }else{
            $info = [];
        }
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }

    /**
     * @param $data
     * @return bool
     * @throws DbException
     */
    public function getCrisisRecode($data): bool
    {
        if(check_array_key('isAbandon',$data)){
            //废弃档案
            $where = [
                ['uid','=',$data['user_id']],
                ['status','=',1],
                ['is_repeal','=',1],
            ];
        }else{
            //正常档案
            $where = [
                ['uid','=',$data['user_id']],
                ['status','=',1],
                ['is_repeal','=',0],
            ];
        }
        $return = InterfereUserModel::query()->where($where)
            ->with(['InterfereBehavior'=>function($query){
                $query->with(['CrisisBehavior']);
            },'CrisisLevel','CrisisType'])
            ->field('id,level_id,type_id,up_num,status,status_time')
            ->order('status_time desc')->paginate($data['pageSize']);
        $ret =$return->toArray();
        # 计算当前页的起始索引
        $start_index = ($ret['current_page'] - 1) * $ret['per_page'];
        // 更新数据并添加 num 字段
        foreach($return as $index => &$item){
            $item['num'] = ($start_index + $index === $ret['total'] - 1) ? 1 : ($ret['total'] - ($start_index + $index));
        }
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }
}